#include "mainwidget.h"
#include "ui_mainwidget.h"

MainWidget::MainWidget(QWidget *parent)
    : QOpenGLWidget(parent),
      texture(QOpenGLTexture::Target2D)
{
    QSurfaceFormat format;
    format.setDepthBufferSize(0);
    format.setStencilBufferSize(0);
    format.setSamples(4);
    setFormat(format);

    timer.setInterval(500);
    connect(&timer, &QTimer::timeout, this, static_cast<void (QWidget::*)()>(&QWidget::repaint));
    timer.start();
}

MainWidget::~MainWidget()
{

}

void MainWidget::initializeGL()
{
    initializeOpenGLFunctions();
    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);

    VAO.create();
    QOpenGLVertexArrayObject::Binder bind(&VAO);
    VBO.create();
    VBO.bind();

    GLfloat vertex[] = {
        //顶点                //纹理坐标
        -1.0f, -1.0f,       0.0f, 0.0f, //左下
        -1.0f, 1.0f,        0.0f, 1.0f,  //左上
         1.0f, -1.0f,       1.0f, 0.0f, //右下
         1.0f, 1.0f,        1.0f, 1.0f,  //右上
    };
    VBO.allocate(vertex, sizeof(vertex));

    shaderProgram.create();
    shaderProgram.addShaderFromSourceFile(QOpenGLShader::Vertex, ":/shader.vert");
    shaderProgram.addShaderFromSourceFile(QOpenGLShader::Fragment, ":/shader.frag");
    shaderProgram.link();

    shaderProgram.enableAttributeArray(0);
    shaderProgram.enableAttributeArray(1);
    shaderProgram.setAttributeBuffer(0, GL_FLOAT, 0,               2, 4*sizeof(GLfloat));
    shaderProgram.setAttributeBuffer(1, GL_FLOAT, 2*sizeof(GLfloat), 2,  4*sizeof(GLfloat));

    VBO.release();
}

void MainWidget::resizeGL(int w, int h)
{
    glViewport(0, 0, w, h);
}

void MainWidget::paintGL()
{
    shaderProgram.bind();
    flushTexture();
    texture.bind(0);
    shaderProgram.setUniformValue("texture", 0);
    QOpenGLVertexArrayObject::Binder bind(&VAO);
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
    shaderProgram.release();
}

void MainWidget::flushTexture()
{
    QString text = QTime::currentTime().toString();
    QFont font("ubuntu", 50);
    QFontMetrics fontMetrics(font);     //QT中用来测量字体的尺寸
    QRect bounding = fontMetrics.boundingRect(text);
    QImage image(bounding.size(), QImage::Format_ARGB32);
    image.fill(Qt::transparent);        //使用透明色填充
    QPainter painter(&image);
    painter.setFont(font);
    painter.setPen(QColor(0, 90, 200));
    painter.drawText(QRect(0, 0, image.width(), image.height()), Qt::AlignCenter, text);
    painter.end();

    if (texture.isCreated())
        texture.destroy();
    texture.create();
    texture.setData(image.mirrored());
}

